package io.renren.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAConfig;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.renren.annotation.Login;
import io.renren.common.constant.Constant;
import io.renren.common.dto.OrdersDTO;
import io.renren.common.dto.PayInfo;
import io.renren.common.dto.UserDTO;
import io.renren.common.entity.OrderDetailEntity;
import io.renren.common.page.PageData;
import io.renren.common.service.OrderDetailService;
import io.renren.common.service.OrdersService;
import io.renren.common.service.ShoppingCartService;
import io.renren.common.service.UserService;
import io.renren.common.utils.Result;
import io.renren.common.utils.SignUtils;
import io.renren.properties.PayConfigProperties;
import io.renren.properties.WeixinProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单模块
 *
 */
@RestController
@RequestMapping("/orders")
@Api(tags="订单模块")
public class ApiOrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private WeixinProperties weixin;

    @Autowired
    private PayConfigProperties payconfig;
    @Autowired
    private UserService userService;
    @Login
    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<OrdersDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){

        PageData<OrdersDTO> page = ordersService.userPage(params);

        return new Result<PageData<OrdersDTO>>().ok(page);
    }

    @Login
    @PostMapping("submit")
    @ApiOperation("提交订单")
    public Result submit(@RequestBody OrdersDTO ordersDTO){
        ordersService.submit(ordersDTO);
        return new Result().ok(null);
    }

    @Login
    @PutMapping("status/{id}")
    @ApiOperation("提交订单")
    public Result status(@PathVariable("id") Long id){
        OrdersDTO ordersDTO = ordersService.get(id);
        ordersDTO.setStatus(2);
        ordersService.update(ordersDTO);
        return new Result().ok(null);
    }

    @Login
    @PostMapping("again")
    @ApiOperation("再来一单")
    @Transactional(rollbackFor = Exception.class)
    public Result again(@RequestBody OrdersDTO ordersDTO){
        if (ordersDTO.getId() != null){
            long id = ordersDTO.getId();
            //获取该订单对应的所有的订单明细表
            List<OrderDetailEntity> orderDetailList = orderDetailService.selectByOrderId(id);
            shoppingCartService.cleanShoppingCart();
            //shoppingCartService.clean();
            shoppingCartService.saveByOrderDetail(orderDetailList);

            return new Result().ok(null);
        }
        return new Result().error("失败!");
    }

    @Login
    @PostMapping("unifiedorder")
    @ApiOperation("订单支付")
    public Result<PayInfo> unifiedorder(@RequestBody OrdersDTO ordersDTO)  {
        try {
//        Config config =
//                new RSAConfig.Builder()
//                        .merchantId(payconfig.getMerchantId())
//                        .privateKeyFromPath(payconfig.getPrivateKeyPath())
//                        .merchantSerialNumber(payconfig.getMerchantSerialNumber())
//                        .wechatPayCertificatesFromPath(payconfig.getWechatPayCertificatePath())
//                        .build();
//        JsapiService service = new JsapiService.Builder().config(config).build();
//        // 调用request.setXxx(val)设置所需参数，具体参数可见Request定义
//        PrepayRequest request = new PrepayRequest();
//        Amount amount = new Amount();
//        amount.setTotal(ordersDTO.getAmount().intValue());
//        request.setAmount(amount);
//        request.setAppid(weixin.getAppid());
//        request.setMchid(payconfig.getMerchantId());
//        request.setDescription("一点美食堡");
//        request.setNotifyUrl("http://localhost:8081/");//这里写自己的网站域名地址
//        request.setOutTradeNo(ordersDTO.getNumber());
//        Payer payer = new Payer();
//        UserDTO userDTO = userService.get(ordersDTO.getUserId());
//        payer.setOpenid(userDTO.getOpenid());
//        request.setPayer(payer);
//        PrepayResponse response = service.prepay(request);
//        System.out.println(response.getPrepayId());

            PayInfo payInfo = new PayInfo();
            payInfo.setAppId(weixin.getAppid());
            payInfo.setTimeStamp((System.currentTimeMillis()/1000));
            payInfo.setNonceStr(RandomStringUtils.randomAlphanumeric(32));
            payInfo.setSignType("MD5");
//       payInfo.setPack("prepay_id="+response.getPrepayId());
            //TODO 因为没有商户号，定死假数据
            payInfo.setPack("prepay_id=wx201410272009395522657a690389285100");
            SignUtils signUtils =new SignUtils(payconfig.getPrivateKey());
//        String sign = signUtils.getSign(payInfo.getAppId(), payInfo.getTimeStamp(), payInfo.getNonceStr(), payInfo.getPack());
//        payInfo.setPaySign(sign);
            //TODO 因为没有商户号，定死假数据
            payInfo.setPaySign("oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq/xDg==");
            //没商户，只能发假数据
            return  new Result<PayInfo>().ok(payInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().error(null);
        }
    }

    @Login
    @PostMapping("orderquery")
    @ApiOperation("交易订单查询")
    public Result orderQuery(@RequestBody OrdersDTO ordersDTO){

//        Config config =
//                new RSAConfig.Builder()
//                        .merchantId(payconfig.getMerchantId())
//                        .privateKeyFromPath(payconfig.getPrivateKeyPath())
//                        .merchantSerialNumber(payconfig.getMerchantSerialNumber())
//                        .wechatPayCertificatesFromPath(payconfig.getWechatPayCertificatePath())
//                        .build();
//        JsapiService service = new JsapiService.Builder().config(config).build();
//
//        QueryOrderByIdRequest queryRequest = new QueryOrderByIdRequest();
//        queryRequest.setMchid(payconfig.getMerchantId());
//        queryRequest.setTransactionId(ordersDTO.getNumber());
//
//        try {
//            Transaction result = service.queryOrderById(queryRequest);
//            System.out.println(result.getTradeState());
//            return new Result().ok(null);
//        } catch (ServiceException e) {
//            // API返回失败, 例如ORDER_NOT_EXISTS
//            System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
//            System.out.printf("reponse body=[%s]\n", e.getResponseBody());
//            return new Result().error(null);
//        }
        return new Result().ok(null);//假定成功
    }


    @DeleteMapping
    @Transactional(rollbackFor = Exception.class)
    public Result deleteOrder(@RequestBody Long id){

        ordersService.deleteOrder(id);
        return new Result().ok(null);
    }


}
